//
//  NSString+Category.m
//  TestButton
//
//  Created by LQiyue on 16/4/28.
//  Copyright © 2016年 LQiyue. All rights reserved.
//

#import "NSString+Category.h"
#import <CommonCrypto/CommonDigest.h>
#import "sys/utsname.h"

#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import  <dlfcn.h>
#import "UIDevice+Info.h"


@implementation NSString (Category)

#pragma mark - userAgent
+ (NSString *)userAgentStr{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    return [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], deviceString, [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)];
}

#pragma mark - URLEncoding
- (NSString *)URLEncoding
{
    NSString * result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault,
                                                                                              (CFStringRef)self,
                                                                                              NULL,
                                                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                              kCFStringEncodingUTF8 ));
    return result;
}


#pragma mark - URLDecoding
- (NSString *)URLDecoding
{
    NSMutableString * string = [NSMutableString stringWithString:self];
    [string replaceOccurrencesOfString:@"+"
                            withString:@" "
                               options:NSLiteralSearch
                                 range:NSMakeRange(0, [string length])];
    return [string stringByRemovingPercentEncoding];
}

#pragma mark - md5Str
- (NSString *)md5Str
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


#pragma mark - urlWithCodePath
//- (NSURL *)urlWithCodePath {
//    NSString *urlStr;
//    if (!self || self.length <= 0) {
//        return nil;
//    }else{
//        if (![self hasPrefix:@"http"]) {
//            urlStr = [NSString stringWithFormat:@"%@%@", [NSObject baseURLStr], self];
//        }else{
//            urlStr = self;
//        }
//        return [NSURL URLWithString:urlStr];
//    }
//}
//- (NSURL *)headerURLWithUID:(NSString *)uid avatarID:(NSString *)avID sizeType:(HeaderPicType)sizeType
//{
//    NSString *urlStr;
//    if (!self || self.length <= 0) {
//        return nil;
//    }
//    if (![self hasPrefix:@"http"]) {
//        CGFloat theSize = 0.0f;
//        switch (sizeType) {
//            case 0:
//                theSize = 50;
//                break;
//            case 1:
//                theSize = 70;
//                break;
//            case 2:
//                theSize = 150;
//                break;
//            case 3:
//                theSize = 640;
//                break;
//
//            default:
//                break;
//        }
//        if ([avID integerValue] < 10000) {
//            //   http://api.club.lenovo.cn/static/avatar/
//            urlStr = [NSString stringWithFormat:@"https://api.club.lenovo.cn/static/avatar/%@.png", avID];
//        } else {
//            if (uid) {
//                NSString *nnn = [NSString stringWithFormat:@"/avatar/%@/%@/0/%ld", uid, avID, (long)theSize];
////                NSString *ss =  [nnn URLEncoding];
////                NSString * string = [NSString stringWithFormat:@"%@%@", PicBaseURL, ss] ;
//
//                NSString *tmp = [NSString stringWithFormat:@"%@%@", kPicCDNDomain, nnn];
//                urlStr = tmp; // string
//            }
//        }
//    }
//
//    NSString * string = urlStr;
//    // 替换图片域名
//    // http://clubimg.lenovo.com.cn
//    if ([string containsString:kPicBaseURL]) {
//        string = [string stringByReplacingOccurrencesOfString:kPicBaseURL withString:kPicCDNDomain];
//    }
//    // http://api.club.lenovo.cn
//    if ([string containsString:kClubDomain]) {
//        string = [string stringByReplacingOccurrencesOfString:kClubDomain withString:kPicCDNDomain];
//    }
//    urlStr = string;
//
//
//    return [NSURL URLWithString:urlStr];
//}
//- (NSURL *)avatarUrl:(NSString *)url
//{
//    if ([url length] > 0) {
//        return [NSURL URLWithString:url];
//    }
//    return nil;
//}
//- (NSURL *)avatarID:(NSString *)avatarID uid:(NSString *)uid
//{
//    NSString *urlStr;
//    if ([avatarID length] > 0 && [avatarID integerValue] < 10000) {
//        urlStr = [NSString stringWithFormat:@"https://api.club.lenovo.cn/static/avatar/%@.png", avatarID];
//    } else {
//        if (uid) {
//            NSString *nnn;
//            if ([avatarID length] > 0) {
//                nnn = [NSString stringWithFormat:@"/avatar/%@/%@/0/%@", uid, avatarID, @"150"];
//                //            NSString *ss =  [nnn URLEncoding];
//                //            NSString * string = [NSString stringWithFormat:@"%@%@", PicBaseURL, ss] ;
//            } else {
//                nnn = [NSString stringWithFormat:@"/avatar/%@/0/%@", uid, @"150"];
//            }
//            NSString *tmp = [NSString stringWithFormat:@"%@%@", kPicCDNDomain, nnn];
//            urlStr = tmp;
//        }
//    }
//    return [NSURL URLWithString:urlStr];
//}
//
//- (NSURL *)pictureURLWithPicID:(NSString *)pic_id sizeType:(PictureType)sizeType
//{
//    NSString *urlStr;
//    if (!self || self.length <= 0) {
//        return nil;
//    }
//    if (![self hasPrefix:@"http"]) {
//        CGFloat theSize = 0.0f;
//        switch (sizeType) {
//            case 0:
//                theSize = 100;
//                break;
//            case 1:
//                theSize = 200;
//                break;
//            case 2:
//                theSize = 640;
//                break;
//            case 3:
//                theSize = 0;
//                break;
//            case 4:
//                theSize = 600;
//                break;
//
//            default:
//                break;
//        }
//        if (pic_id) {
//
//            NSString *nnn = [NSString stringWithFormat:@"/pic/%@/%ld", pic_id, (long)theSize];
////            NSString *ss =  [nnn URLEncoding];
////            NSString * string = [NSString stringWithFormat:@"%@%@", PicBaseURL, ss] ;
//            NSString *tmp = [NSString stringWithFormat:@"%@%@", kPicCDNDomain, nnn];
//            urlStr = tmp;
//        }
////        DebugLog(@"1111图片拼接 %@", urlStr);
//    } else {
//        if ([pic_id containsString:@"http"]) {
//
//            urlStr = pic_id;
//        }
//    }
//    return [NSURL URLWithString:urlStr];
//}
//- (NSURL *)mohuPictureURLWithPicID:(NSString *)pic_id sizeType:(PictureType)sizeType
//{
//    NSString *urlStr;
//    if (!self || self.length <= 0) {
//        return nil;
//    }
//    if (![self hasPrefix:@"http"]) {
//        CGFloat theSize = 0.0f;
//        switch (sizeType) {
//            case 0:
//                theSize = 100;
//                break;
//            case 1:
//                theSize = 200;
//                break;
//            case 2:
//                theSize = 640;
//                break;
//            case 3:
//                theSize = 0;
//                break;
//            case 4:
//                theSize = 600;
//                break;
//
//            default:
//                break;
//        }
//        if (pic_id) {
//
//            NSString *nnn = [NSString stringWithFormat:@"/pic/blur/%@/%ld", pic_id, (long)theSize];
////            NSString *ss =  [nnn URLEncoding];
////            NSString * string = [NSString stringWithFormat:@"%@%@", PicBaseURL, ss] ;
//            NSString *tmp = [NSString stringWithFormat:@"%@%@", kPicCDNDomain, nnn];
//            urlStr = tmp;
//        }
//        DebugLog(@"图片拼接 %@", urlStr);
//    }
//    return [NSURL URLWithString:urlStr];
//}


- (CGSize)getSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
    CGSize resultSize = CGSizeZero;
    if (self.length <= 0) {
        return resultSize;
    }
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        resultSize = [self boundingRectWithSize:size
                                        options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{NSFontAttributeName: font}
                                        context:nil].size;
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        resultSize = [self sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
#endif
    }
    resultSize = CGSizeMake(MIN(size.width, ceilf(resultSize.width)), MIN(size.height, ceilf(resultSize.height)));
    return resultSize;
    
    
}
- (CGSize)getSizeWithAttribute:(NSDictionary *)attribute constrainedToSize:(CGSize)size{
    CGSize resultSize = CGSizeZero;
    if (self.length <= 0) {
        return resultSize;
    }
    
    resultSize = [self boundingRectWithSize:size
                                    options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                 attributes:attribute
                                    context:nil].size;
    
    return resultSize;
    
    
}

- (CGFloat)getHeightWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
    return [self getSizeWithFont:font constrainedToSize:size].height;
}
- (CGFloat)getWidthWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
    return [self getSizeWithFont:font constrainedToSize:size].width;
}

//- (NSURL *)urlImageWithCodePathResize:(CGFloat)width{
//    return [self urlImageWithCodePathResize:width crop:NO];
//}
//- (NSString *)stringByRemoveHtmlTag{
    //    HtmlMedia *media = [HtmlMedia htmlMediaWithString:self showType:MediaShowTypeImageAndMonkey];
    //    return media.contentDisplay;
//    return nil;
//}
//- (NSURL *)urlImageWithCodePathResize:(CGFloat)width crop:(BOOL)needCrop{
//    NSString *urlStr;
//    BOOL canCrop = NO;
//    if (!self || self.length <= 0) {
//        return nil;
//    }else{
//        if (![self hasPrefix:@"http"]) {
//            NSString *imageName;
//            // #import "RegexKitLite.h"
//            //           imageName = [self stringByMatching:@"/static/fruit_avatar/([a-zA-Z0-9\\-._]+)$" capture:1];
//            if (imageName && imageName.length > 0) {
//                urlStr = [NSString stringWithFormat:@"http://LenovoClub-net-avatar.qiniudn.com/%@?imageMogr2/auto-orient/thumbnail/!%.0fx%.0fr", imageName, width, width];
//                canCrop = YES;
//            }else{
//                urlStr = [NSString stringWithFormat:@"%@%@", [NSObject baseURLStr], self];
//            }
//        }else{
//            urlStr = self;
//            if ([urlStr rangeOfString:@"qbox.me"].location != NSNotFound) {
//                if ([urlStr rangeOfString:@".gif"].location != NSNotFound) {
//                    if ([urlStr rangeOfString:@"?"].location != NSNotFound) {
//                        urlStr = [urlStr stringByAppendingString:[NSString stringWithFormat:@"/thumbnail/!%.0fx%.0fr/format/png", width, width]];
//                    }else{
//                        urlStr = [urlStr stringByAppendingString:[NSString stringWithFormat:@"?imageMogr2/auto-orient/thumbnail/!%.0fx%.0fr/format/png", width, width]];
//                    }
//                }else{
//                    if ([urlStr rangeOfString:@"?"].location != NSNotFound) {
//                        urlStr = [urlStr stringByAppendingString:[NSString stringWithFormat:@"/thumbnail/!%.0fx%.0fr", width, width]];
//                    }else{
//                        urlStr = [urlStr stringByAppendingString:[NSString stringWithFormat:@"?imageMogr2/auto-orient/thumbnail/!%.0fx%.0fr", width, width]];
//                    }
//                }
//                canCrop = YES;
//            }else if ([urlStr rangeOfString:@"www.gravatar.com"].location != NSNotFound){
//                urlStr = [urlStr stringByReplacingOccurrencesOfString:@"s=[0-9]*" withString:[NSString stringWithFormat:@"s=%.0f", width] options:NSRegularExpressionSearch range:NSMakeRange(0, [urlStr length])];
//            }else if ([urlStr hasSuffix:@"/imagePreview"]){
//                urlStr = [urlStr stringByAppendingFormat:@"?width=%.0f", width];
//            }
//        }
//        if (needCrop && canCrop) {
//            urlStr = [urlStr stringByAppendingFormat:@"/gravity/Center/crop/%.0fx%.0f", width, width];
//        }
//        return [NSURL URLWithString:urlStr];
//    }
//}
//- (NSURL *)urlImageWithCodePathResizeToView:(UIView *)view{
//    return [self urlImageWithCodePathResize:2*CGRectGetWidth(view.frame)];
//}

+ (NSString *)handelRef:(NSString *)ref path:(NSString *)path{
    if (ref.length <= 0 && path.length <= 0) {
        return nil;
    }
    
    NSMutableString *result = [NSMutableString new];
    if (ref.length > 0) {
        [result appendString:ref];
    }
    if (path.length > 0) {
        [result appendFormat:@"%@%@", ref.length > 0? @"/": @"", path];
    }
    return [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


-(BOOL)containsEmoji{
    if (!self || self.length <= 0) {
        return NO;
    }
    __block BOOL returnValue = NO;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}
#pragma mark -
+ (NSDictionary *)emotion_Lenovo_dict {
    static NSDictionary *_emotion_Lenovo_dict;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _emotion_Lenovo_dict = @{
                                 
                                 };
    });
    return _emotion_Lenovo_dict;
}
- (NSString *)emotionMonkeyName{
    return [NSString emotion_Lenovo_dict][self];
}

+ (NSString *)sizeDisplayWithByte:(CGFloat)sizeOfByte{
    NSString *sizeDisplayStr;
    if (sizeOfByte < 1024) {
        sizeDisplayStr = [NSString stringWithFormat:@"%.2f bytes", sizeOfByte];
    }else{
        CGFloat sizeOfKB = sizeOfByte/1024;
        if (sizeOfKB < 1024) {
            sizeDisplayStr = [NSString stringWithFormat:@"%.2f KB", sizeOfKB];
        }else{
            CGFloat sizeOfM = sizeOfKB/1024;
            if (sizeOfM < 1024) {
                sizeDisplayStr = [NSString stringWithFormat:@"%.2f M", sizeOfM];
            }else{
                CGFloat sizeOfG = sizeOfKB/1024;
                sizeDisplayStr = [NSString stringWithFormat:@"%.2f G", sizeOfG];
            }
        }
    }
    return sizeDisplayStr;
}

- (NSString *)trimWhitespace
{
    NSMutableString *str = [self mutableCopy];
    CFStringTrimWhitespace((__bridge CFMutableStringRef)str);
    return str;
}

- (BOOL)isEmpty
{
    return [[self trimWhitespace] isEqualToString:@""];
}

- (BOOL)isEmptyOrListening{
    return [self isEmpty] || [self hasListenChar];
}

//判断是否为整形
- (BOOL)isPureInt{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形
- (BOOL)isPureFloat{
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

- (NSRange)rangeByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet{
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer];
    for (location = 0; location < length; location++) {
        if (![characterSet characterIsMember:charBuffer[location]]) {
            break;
        }
    }
    return NSMakeRange(location, length - location);
}
- (NSRange)rangeByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet{
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer];
    for (length = [self length]; length > 0; length--) {
        if (![characterSet characterIsMember:charBuffer[length - 1]]) {
            break;
        }
    }
    return NSMakeRange(location, length - location);
}

- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
    return [self substringWithRange:[self rangeByTrimmingLeftCharactersInSet:characterSet]];
}

- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
    return [self substringWithRange:[self rangeByTrimmingRightCharactersInSet:characterSet]];
}

//转换拼音
- (NSString *)transformToPinyin {
    if (self.length <= 0) {
        return self;
    }
    NSString *tempString = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)tempString, NULL, kCFStringTransformToLatin, false);
    tempString = (NSMutableString *)[tempString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    tempString = [tempString stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [tempString uppercaseString];
}

//是否包含语音解析的图标
- (BOOL)hasListenChar {
    BOOL hasListenChar = NO;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer];
    for (length = [self length]; length > 0; length--) {
        if (charBuffer[length -1] == 65532) {   //'\U0000fffc'
            hasListenChar = YES;
            break;
        }
    }
    return hasListenChar;
}

+(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}

+ (NSString *)convertWithArray:(NSString *)array {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array
                                                       options:kNilOptions
                                                         error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    return jsonString;
}

-(NSString *)handleEmptyStr {
    if (self.length) {
        return self;
    }
    return @"";
}

- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW {
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    CGSize size = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:attrs context:nil].size;
    size = CGSizeMake(ceil(size.width), size.height);
    return size;
}

+ (BOOL)isEmpty:(NSString *)str {
    if (!str.length) {
        return YES;
    }else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if (!trimedString.length) {
            return YES;
        }
    }
    return NO;
}

- (NSString *)handlePointZero {
    NSString *str = nil;
    NSArray *itemArr = [self componentsSeparatedByString:@"."];
    if (itemArr.count > 1) {
        if (![itemArr[1] intValue]) {
            str = [NSString stringWithFormat:@"%d",self.intValue];
        }
    }
    
    return str;
}

- (NSString *)pointStr {
    NSArray *itemArr = [self componentsSeparatedByString:@"."];
    if (itemArr.count > 1) {
        return itemArr[1];
    }
    return @"";
}

- (NSString *)priceValue {
    NSArray *valueArr = [self componentsSeparatedByString:@"."];
    if (valueArr.count == 2) {
        if ([valueArr[1] isEqualToString:@"00"] || [valueArr[1] isEqualToString:@"0"]) {
            return valueArr[0];
        }
        return self;
    }return self;
}
+ (NSString*)saveImageToLocal:(UIImage *)image
{
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"lenovo_share_play_bill.png"]];  // 保存文件的名称
    BOOL result =[UIImagePNGRepresentation(image)writeToFile:filePath   atomically:YES]; // 保存成功会返回YES
    if (result == YES) {
        return filePath;
    }
    return nil;
}
- (NSString *)stringFromMD5 {
    
    if(self == nil || [self length] == 0)
        return nil;
    
    const char *value = [self UTF8String];
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (CC_LONG)strlen(value), outputBuffer);
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    return outputString;
}


+ (NSString *)randomWithLenth:(int)randomLength
{
    static char *RANDOM_STR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static int RANDOM_STR_LEN = 62;
    NSMutableData* tmpBuf = [NSMutableData dataWithLength:randomLength];
    char* tmpPointer = [tmpBuf mutableBytes];
    for (int i = 0; i < randomLength; i++)
    {
        tmpPointer[i] = RANDOM_STR[arc4random() % RANDOM_STR_LEN];
    }
    NSString* result = [[NSString alloc] initWithData:tmpBuf encoding:NSASCIIStringEncoding];

    return result;
}
static NSString *DeviceIdKey = @"deviceId";
+ (NSString *)deviceId
{
    NSString *theDeviceId = [[NSUserDefaults standardUserDefaults] stringForKey:DeviceIdKey];
    if (nil == theDeviceId) {
        theDeviceId = [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier];
        [[NSUserDefaults standardUserDefaults] setValue:theDeviceId forKey:DeviceIdKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    return theDeviceId;
}


#pragma mark - 获取当前连接的WiFi以及IP地址
//获取手机的网络的ip地址
+ (NSString *)getIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                DebugLog(@">>>>>>>>>>>>>IP name = %@", name);
                if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
                {
                    DebugLog(@"IP:%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]);
                }
                NSString *IP =  [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                DebugLog(@">>>>>>>>>>>>>IP = %@", IP);
                return IP;
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

@end
